package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import com.ruoyi.teaching.domain.vo.PhoneMessageVO;
import com.ruoyi.teaching.service.MailService;
import com.ruoyi.teaching.utils.VerifyCodeUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MailServiceImpl implements MailService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private VerifyCodeUtil verifyCodeUtil;


    @Override
    public String sendEmail(String email) {
        if (StringUtils.isBlank(email)) {
            throw new RuntimeException("未填写收件人邮箱");
        }
        // 定义Redis的key
        String key = "msg_" + email;
        String countKey = "msg_count_" + email; // 定义计数器 key
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        // 检查计数器是否超出限制
        String countStr = valueOperations.get(countKey);
        int count = countStr == null ? 0 : Integer.parseInt(countStr);
        if (count >= 3) {
            return "操作过于频繁，请稍后再试。感谢您的理解与配合！";
        }
        // String verifyCode = valueOperations.get(key);
        // if (verifyCode == null) {
        // 随机生成一个6位数字型的字符串
        String code = verifyCodeUtil.generateVerifyCode(6);
        // 邮件对象（邮件模板，根据自身业务修改）
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("伟达数字教学云平台注册邮箱验证码");
        message.setText("尊敬的用户您好!\n\n感谢您注册伟达数字教学云平台\n\n尊敬的: " + email + "您的校验验证码为: " + code + ",有效期5分钟，请不要把验证码信息泄露给其他人,如非本人请勿操作");
        message.setTo(email);
        try {
            // 对方看到的发送人（发件人的邮箱，根据实际业务进行修改，一般填写的是企业邮箱）
            message.setFrom(new InternetAddress(MimeUtility.encodeText("伟达官方") + "<3172908530@qq.com>").toString());
            // 发送邮件
            javaMailSender.send(message);
            // 将生成的验证码存入Redis数据库中，并设置过期时间
            valueOperations.set(key, code, 5L, TimeUnit.MINUTES);

            // 缓存计数器并递增
            if (countStr == null) {
                valueOperations.set(countKey, "1", 5L, TimeUnit.MINUTES);
            } else {
                valueOperations.increment(countKey);
            }

            log.info("邮件发送成功");
            return "邮件发送成功";
        } catch (Exception e) {
            log.error("邮件发送出现异常");
            log.error("异常信息为" + e.getMessage());
            log.error("异常堆栈信息为-->");
            if(e.getMessage().contains("The recipient may contain a non-existent account, please check the recipient address")){
                return "邮箱不存在，请检查后重试";
            }
            return "邮件发送失败";
            // e.printStackTrace();
            // throw new RuntimeException(e);
        }
        // } else {
        //     return "验证码已发送至您的邮箱，请注意查收";
        // }
    }

    @Override
    public String sendPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new RuntimeException("未填写收件人邮箱");
        }
        // 定义Redis的key
        String key = "msg_" + phone;
        String countKey = "msg_count_" + phone; // 定义计数器 key
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        // 检查计数器是否超出限制
        String countStr = valueOperations.get(countKey);
        int count = countStr == null ? 0 : Integer.parseInt(countStr);
        if (count >= 3) {
            return "操作过于频繁，请稍后再试。感谢您的理解与配合！";
        }
        // String verifyCode = valueOperations.get(key);
        // if (verifyCode == null) {
        try {
            // 模板id 2192235 //SDK AppID 1400919297     App Key b3a392a7e6684c2b17c5b8aade64dc2b
            // SecretId AKIDeBcr01HpZUbrSEzfFj2YDoVWQEIPM6oU  SecretKey：1sj5a2XK5kJ61tdKBIYUMCC8uTwLYbXL
            // 创建 COSCredentials 对象，传入 SecretId 和 SecretKey --- 密钥
            Credential cred = new Credential("AKIDeBcr01HpZUbrSEzfFj2YDoVWQEIPM6oU", "1sj5a2XK5kJ61tdKBIYUMCC8uTwLYbXL");
            HttpProfile httpProfile = new HttpProfile();
            // 设置腾讯云服务 API 的访问域名
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            // 设置 HTTP 的请求配置信息
            clientProfile.setHttpProfile(httpProfile);
            // 指定 SMS 所在的区域
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            // 接收短信的手机号码，可以设置多个
            String[] phoneNumberSet1 = {"+86" + phone};
            req.setPhoneNumberSet(phoneNumberSet1);

            // 设置正文模板 ID
            req.setTemplateID("2192976");
            // 设置短信应用 ID
            req.setSmsSdkAppid("1400919297");
            // 设置签名内容
            req.setSign("河南伟达电子技术有限公司");

            // 调用生成验证码的工具类
            String code = verifyCodeUtil.generateVerifyCode(6);

            // 短信模板中的参数，需与短信模板中的参数个数一致
            String[] templateParams = {code, "5"};
            req.setTemplateParamSet(templateParams);
            // 发送短信
            SendSmsResponse resp = client.SendSms(req);
            Gson gson = new Gson();
            PhoneMessageVO phoneMessageVO = gson.fromJson(SendSmsResponse.toJsonString(resp), PhoneMessageVO.class);

            if (phoneMessageVO.getSendStatusSet().get(0).getCode().equals("Ok")) {
                // 缓存验证码
                valueOperations.set(key, code, 5L, TimeUnit.MINUTES);

                // 缓存计数器并递增
                if (countStr == null) {
                    valueOperations.set(countKey, "1", 5L, TimeUnit.MINUTES);
                } else {
                    valueOperations.increment(countKey);
                }
            } else {
                return "验证码发送失败,请检查手机号";
            }
            System.out.println(SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return "验证码已发送至您的手机，请注意查收";
        // } else {
        //
        //     return "验证码已发送至您的手机，请"+stringRedisTemplate.getExpire(key, TimeUnit.SECONDS) + "秒后尝试";
        // }
    }
}
